package com.wenjunwu.blog.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;
import com.wenjunwu.blog.common.PageTranslate;
import com.wenjunwu.blog.common.SnowFlake;
import com.wenjunwu.blog.em.OptionEnum;
import com.wenjunwu.blog.entity.BlogComment;
import com.wenjunwu.blog.entity.BlogContent;
import com.wenjunwu.blog.service.BlogCommentService;
import com.wenjunwu.blog.service.BlogContentService;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class BlogContentController {

	@Autowired
	private BlogContentService blogContentService;

	@Autowired
	private BlogCommentService blogCommentService;
	
	private SnowFlake snowFlake = new SnowFlake(0, 0);

	@RequestMapping(path = { "/", "/portal", "/portal/index" })
	public ModelAndView showBlogs() {
		ModelAndView mav = new ModelAndView();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", "publish");
		Map<String, List<BlogContent>> summaries = blogContentService.selectSummarys(params, "section");
		mav.addAllObjects(summaries);
		mav.setViewName("portal/index");
		return mav;
	}
	
	@RequestMapping(path = { "console/toArticles" })
	public ModelAndView toArticles() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("console/blogs");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(path = { "/console/articles"})
	public PageTranslate<BlogContent> articles(HttpServletRequest request) {
		String temp = request.getParameter("draw") == null ? "1" : request.getParameter("draw");
		String paramPageNum = request.getParameter("start") == null ? "1" : request.getParameter("start");
		Integer pageSize = Integer.valueOf(request.getParameter("length") == null ? "10" : request.getParameter("length"));
		int pageNum = (Integer.valueOf(paramPageNum) / pageSize + 1);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", "publish");
		Page<BlogContent> blogPage = blogContentService.findBlogPage(pageNum, pageSize,params);
		PageTranslate<BlogContent> pageTranslate = new PageTranslate<BlogContent>();
		List<BlogContent> result = blogPage.getResult();
		pageTranslate.setData(result);
		pageTranslate.setDraw(Long.valueOf(temp));
		pageTranslate.setRecordsTotal(blogPage.getTotal());
		pageTranslate.setRecordsFiltered(blogPage.getTotal());
		return pageTranslate;
	}

	@RequestMapping(path = {"/{srcfrom}/detail/{id}"})
	public ModelAndView getBlog(@PathVariable String srcfrom, @PathVariable Long id) {
		ModelAndView mav = new ModelAndView();
		BlogContent blogContent = blogContentService.selectByPrimaryKey(id);
		Map<String, Object> params = new HashMap<String, Object>();
		if(OptionEnum.OPTION_PORTAL.getValue().equalsIgnoreCase(srcfrom)) {
			params.put("status", "publish");
			params.put("contentId", id);
			List<BlogComment> blogComments = blogCommentService.find(params);
			mav.addObject(blogComments);
		}
		mav.addObject(blogContent);
		mav.setViewName(srcfrom.concat("/detail"));
		return mav;
	}

	@RequestMapping(path = { "/portal/list/", "/portal/list/{catagory}" })
	public ModelAndView lang(@PathVariable(required = false) String catagory) {
		ModelAndView mav = new ModelAndView();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", "publish");
		if (!StringUtils.isEmpty(catagory)) {
			params.put("catagory", catagory);
		}
		List<BlogContent> blogContents = blogContentService.getBlogsByParams(params);
		mav.addObject(blogContents);
		mav.setViewName("portal/list");
		return mav;
	}

	@RequestMapping(path = "/console/initPub", method = RequestMethod.GET)
	public ModelAndView publish() {
		ModelAndView mav = new ModelAndView("console".concat("/").concat("blogpub"));
		return mav;
	}
	
	@RequestMapping(value = "/console/publish", method = RequestMethod.POST)
	public String add(HttpServletRequest request) {
		blogContentService.save(request);
		return "redirect:/index";
	}

	@ResponseBody
	@RequestMapping(value = "/console/upload", method = RequestMethod.POST)
	public Map<String, String> upload(MultipartFile photo, HttpServletRequest request, HttpServletResponse response) {

		String serverPath = request.getSession().getServletContext().getContextPath();
		String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/uploadFile");

		Map<String, String> map = new HashMap<String, String>();
		try {
			// 存储文件夹
			if (photo == null) {
				return null;
			}
			String rawFileName = photo.getOriginalFilename();
			// 新文件名称
			long nextId = snowFlake.nextId();
			String newFileName = String.valueOf(nextId).concat(rawFileName.substring(rawFileName.length() - 4, rawFileName.length()));
			// 保存路径
			File file = new File(realPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			File rawImage = new File(realPath, rawFileName);
			File compressImage=new File(realPath, newFileName);
			photo.transferTo(rawImage);
			Thumbnails.of(rawImage).scale(1f).outputQuality(0.5f).toFile(compressImage);
			rawImage.delete();
			// 返回客户端的JSON
			map.put("success", "true");
			map.put("msg", "成功");
			// 返回服务器地址
			map.put("file_path", serverPath.concat("/uploadFile/").concat(newFileName));
		} catch (IOException e) {
			map.put("success", "false");
		}
		return map;
	}

}
